import logging
from extensions.ext_database import db
from models.robot.intent_reco import IntentRecGroup, IntentRecoTerms, RobFuncs
from services.robot.intent_remote_service import IntentRemoteService
class IntentBuildService:
    @staticmethod
    def has_mission(group_id:str)->bool:
        group = db.session.get(IntentRecGroup, group_id)
        if not group:
            return False
        if not group.dataset_id or not group.document_id:
            return False
        task_info = IntentRemoteService.link_terms_to_group_task_status(group.dataset_id,group.document_id)
        if task_info.get("status")=="running":
            return True
        return False
    
    @staticmethod
    def link_funcs_to_group(group_id,func_ids:list[str],all_terms:bool=False)->tuple[bool,str]:
        group = db.session.get(IntentRecGroup, group_id)
        if not group:
            return False,"Group not found"
        if not group.dataset_id or not group.document_id:
            return False,"Group not Initialized"
        dataset_id = str(group.dataset_id) 
        document_id = str(group.document_id)
        func_terms = {}
        funcs = db.session.query(RobFuncs).filter(RobFuncs.id.in_(func_ids)).all()
        for func in funcs:
            func_terms[str(func.id)] = []
            query = db.session.query(IntentRecoTerms).filter(IntentRecoTerms.cmd_id==func.id)
            if not all_terms:
                query = query.filter(IntentRecoTerms.status!='d')
            terms = query.all()
            for term in terms:
                func_terms[str(func.id)].append({"term_id":term.id,"term":term.term})
        
        result = IntentRemoteService.link_terms_to_group(dataset_id,document_id,func_terms)
        if result.get("code")==200:
            return True,result.get("message","")
        return False,result.get("message","")
    
    @classmethod
    def link_terms_to_group_task_status(cls,group_id:str)->dict:
        group = db.session.get(IntentRecGroup, group_id)
        if not group:
            return {"status":False,"message":"Group not found"}
        if not group.dataset_id or not group.document_id:
            return {"status":False,"message":"Group not Initialized"}
        dataset_id = str(group.dataset_id) 
        document_id = str(group.document_id)
        result = IntentRemoteService.link_terms_to_group_task_status(dataset_id,document_id)
        if result.get("status",None) == "finished":
            link_result = result.get("result",{})
            terms = link_result.get("terms",[])
            term_ids = [k for k,v in terms]
            try:
                db.session.query(IntentRecoTerms).filter(IntentRecoTerms.id.in_(term_ids)).update({"status":'d'})
                db.session.commit()
            except Exception as e:
                logging.error(e)
        return result
